package com.zm.spring.jdbc.dao;

import com.zm.spring.jdbc.Bean.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    public void insert(Account account){
        jdbcTemplate.update("insert into bank_account values(?,?,?)",
                account.getId(),
                account.getPassword(),
                account.getBalance());
    }

    public void updateById(Account account){
        System.out.println("account = " + account);
        jdbcTemplate.update("update bank_account set balance = ? where id = ?",
                account.getBalance(),
                account.getId());
    }
    public Account selectById(int id){
        Account account = jdbcTemplate.queryForObject("select * from bank_account where id = ?",
                new RowMapper<Account>() {
                    @Override
                    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Account account = new Account();
                        account.setId(rs.getInt("id"));
                        account.setPassword(rs.getString("password"));
                        account.setBalance(rs.getDouble("balance"));
                        return account;
                    }
                },
                id);
        return account;
    }

    public Account selectByAccount(Account account){
        Account account1 = jdbcTemplate.queryForObject("select * from bank_account where id = ? and password = ?",
                new RowMapper<Account>() {
                    @Override
                    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Account account = new Account();
                        account.setId(rs.getInt("id"));
                        account.setPassword(rs.getString("password"));
                        account.setBalance(rs.getDouble("balance"));
                        return account;
                    }
                },
                account.getId(),account.getPassword());
        return account1;
    }

    public List<Account> selectAll(){
        List<Account> list = jdbcTemplate.query("select * from bank_account",
                new BeanPropertyRowMapper<Account>(Account.class));
        return list;
    }


}
